<template>
  <!-- select 联动 -->
  <select-base
    v-model="vValue"
    v-bind="attrs"
    :row="row"
    :options="selectList"
    @itemEvent="itemEvent"
  ></select-base>
</template>

<script setup>
import { vModelValue } from '@/utils/hooks.js';
import SelectBase from './SelectBase.vue';
import { apiMethods } from '@/utils/http.js';

const attrs = useAttrs();

const props = defineProps({
  modelValue: {
    type: [String, Array, Number],
  },
  options: {
    // 下拉值集合
    type: Array,
    default: () => [],
  },
  requestUrl: {
    // 下拉接口
    type: String,
    default: '',
  },
  tierData: {
    // 调用接口获取数据的层级关系
    type: String,
    default: '',
  },
  params: {
    // 固定传参
    type: Object,
    default: () => ({}),
  },
  axiosMethod: {
    // 请求方式
    type: String,
    default: 'post',
  },
  row: {
    // form数据,或者table的行数据
    type: Object,
    default: () => ({}),
  },
  dynamicParam: {
    // 动态参数取值key集合,
    type: Array,
    default: () => [],
  },
  rowSelectKey: {
    // 从table行获取下拉值的取值字段
    type: String,
    default: '',
  },
  isInitData: {
    // 初始化是否加载数据
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(['update:modelValue', 'itemEvent']);
const { newValue: key } = vModelValue(props, emits);
let vValue = ref(key);

let requestList = ref([]);

onMounted(() => {
  if (props.isInitData && props.requestUrl) getDataList();
});

// 下拉值过滤
const selectList = computed(() => {
  let list = [];
  if (props.options?.length) {
    list = [...props.options];
  } else if (props.requestUrl) {
    list = [...requestList.value];
  }
  if (props.rowSelectKey && !list.length) {
    list = props.row[attrs.rowSelectKey] || [];
  }
  return list;
});

// 请求接口
async function getDataList(init = false) {
  if (!init) {
    vValue.value = '';
  }
  // 获取动态参数
  let flagParams = {};
  props.dynamicParam.forEach(item => {
    if (item.label) {
      // definiteValue 固定值
      flagParams[item.label] = item.definiteValue ? item.definiteValue : props.row[item.value];
    } else {
      flagParams[item] = props.row[item];
    }
  });
  let res = await apiMethods[props.axiosMethod](props.requestUrl, {
    ...props.params,
    ...flagParams,
  });
  requestList.value = [];
  let code = '';
  let arr = [];
  if (props.tierData) {
    let tierArr = props.tierData.split('.');
    let tierLen = tierArr.length;
    tierArr.forEach((item, index) => {
      arr = arr ? arr[item] : res[item];
      if (index == tierLen - 2) {
        code = arr.code;
      }
    });
  } else {
    code = res.data.code || res.data.errorCode;
    arr = res.data.data || [];
  }
  if (code == 200) requestList.value = arr;
}

function itemEvent(scope) {
  emits('itemEvent', scope);
}

defineExpose({
  getDataList,
});
</script>
